import O1HD, {managers, modules, services} from "../engines/gameEngine";
import {oneSonLoadProgress, RESOURCES_TYPE} from "./loading/loadConfig_json";
import {GameModeDetail} from "../engines/managers/gameManager";
import gameConfig from "../engines/configs/gameConfig";
import logScreen from "../O1ModuleRes/frame/logScreen";
import mainRoot from "../Game/MainRoot";
import { PAGE } from "../Game/Enum";
import loadingAni from "../O1ModuleRes/control/loadingAni";
import CsvDataManage from "../engines/managers/CsvDataManage";

let {ccclass, property} = cc._decorator;

@ccclass
export default class loading extends cc.Component {

    @property({displayName: '预加载场景', tooltip: '是否预先加载大厅和游戏场景'})
    pmPreLoadScenes = true;

    @property({type: cc.ProgressBar, displayName: '进度条'})
    pmLoadBar: cc.ProgressBar = null;

    @property({type: cc.ProgressBar, displayName: '子进度条'})
    pmSonLoadBar: cc.ProgressBar = null;

    @property({displayName: '是否显示子进度条'})
    isShowSonBar: boolean = true;

    @property({displayName: '子进度条加载条数'})
    sonLoadCount: number = 100;

    @property({type: cc.Label, displayName: '进度文字'})
    pmLoadLabel: cc.Label = null;

    @property({type:loadingAni,displayName:"加载中动画"})
    loadingAni:loadingAni = null;

    @property({type:cc.Node,displayName:""})
    logo:cc.Node = null;

    @property({type:cc.Node,displayName:""})
    startBtn:cc.Node = null;

    @property({type:cc.Node,displayName:""})
    newBtn:cc.Node = null;

    @property({type:cc.Node,displayName:"关注抖音号"})
    attentionBtn:cc.Node=null;

    protected start() {
    }

    onLoad() {
        new CsvDataManage();
        if(loading.isLoaded){
            let mainSceneName = managers().gameMgr.getMainSceneNameAndLoadBundle();
            if (typeof mainSceneName === 'string') {
                this.preLoadSceneOver(mainSceneName);
            } else {
                this.preLoadSceneOver(mainSceneName.sceneName);
            }
        }else{
            //
            this.pmLoadBar.progress = 0;
            this.pmLoadLabel.string = `正在初始化`;
            this.pmSonLoadBar.progress = 0;
            this.pmSonLoadBar.node.active = this.isShowSonBar;
            // this.startBtn.active = false;
            // this.newBtn.active =false;
            // this.attentionBtn.active=false;

            // this.logo.active = false;
            // this.loadingAni.node.active = true;
            //
            this.loadPackages();
        }
    }
    
    protected onEnable(): void {
        
    }

    loadPackages() {
        //
        this.loadSubpackages().then(() => {
            //
            let mainSceneName = managers().gameMgr.getMainSceneNameAndLoadBundle();
            if (typeof mainSceneName === 'string') {
                this.preLoadSceneOver(mainSceneName);
            } else {
                this.preLoadSceneOver(mainSceneName.sceneName);
            }
        });
    }

    private m_allPreloadResources: oneSonLoadProgress[] = [];

    async onAddLogServiceNode(): Promise<void> {
        return new Promise(resolve => {
            if (gameConfig.LOG_SERVICE_OPEN &&
                gameConfig.SCREEN_LOG_SWITCH) {
                modules().uiControlModule.showFramePrefab('preload/frame/logScreen', O1HD.Canvas().parent, false, node => {
                    services().logSrv.addScreenPrint(node.getComponent(logScreen));
                    resolve();
                });
            } else {
                resolve();
            }
        });
    }

    async loadSubpackages() {
        //
        await O1HD.loadAll();
        //
        await this.loadAllPreloadResources();
        //
        await this.onAddLogServiceNode();
        //
        return Promise.resolve();
    }

    //初始化要加载的数据
    initPreloadResources() {
        // O1HD.getManagers().soundMgr.loadSoundBundle();
        //配置
        this.m_allPreloadResources = [];
        //框架包
        this.m_allPreloadResources.push({
            resourcesType: RESOURCES_TYPE.BUNDLE,
            resPathOrName: modules().uiControlModule.getFrameBundlePath(),
            loadText: '加载框架资源',
            onBundleLoaded: bundle => {
                modules().uiControlModule.setFrameBundle(bundle);
            },
        });
        //框架资源
        this.m_allPreloadResources.push({
            resourcesType: RESOURCES_TYPE.ASSETS,
            resPathOrName: modules().uiControlModule.getFrameBundlePreloadResPath(),
            loadText: '加载框架资源',
            bundle: () => {
                return modules().uiControlModule.getFrameBundle();
            },
        });
        //游戏包
        this.m_allPreloadResources.push({
            resourcesType: RESOURCES_TYPE.BUNDLE,
            resPathOrName: modules().uiControlModule.getGameBundlePath(),
            loadText: '加载游戏公共资源',
            onBundleLoaded: bundle => {
                modules().uiControlModule.setGameBundle(bundle);
            },
        });
        //游戏资源
        this.m_allPreloadResources.push({
            resourcesType: RESOURCES_TYPE.ASSETS,
            resPathOrName: modules().uiControlModule.getGameBundlePreloadResPath(),
            loadText: '加载游戏资源',
            bundle: () => {
                return modules().uiControlModule.getGameBundle();
            },
        });
        //游戏主音效
        this.m_allPreloadResources.push({
            resourcesType:RESOURCES_TYPE.BUNDLE,
            resPathOrName:"mainSound",
            loadText:"加载游戏音效",            
            onBundleLoaded: bundle => {
                managers().soundMgr.addOneSoundBundle("mainSound",bundle);
            },
        });

        //hall分包
        this.m_allPreloadResources.push({
            resourcesType: RESOURCES_TYPE.BUNDLE,
            resPathOrName: 'hall',
            loadText: '加载总场景资源',
        })
        //主场景资源
        let mainSceneBundle = managers().gameMgr.getMainSceneNameAndLoadBundle();
        if (null == mainSceneBundle) {
            console.error('#69 主场景配置错误');
        }
        //主场景 为 hall
        if (mainSceneBundle === 'hall') {
            this.m_allPreloadResources.push({
                resourcesType: RESOURCES_TYPE.SCENE,
                resPathOrName: mainSceneBundle,
                loadText: '加载主场景'
            })
            //否则就调用其他子包
        } else {
            let bundleInfo = <GameModeDetail>mainSceneBundle;
            //先加载子包
            this.m_allPreloadResources.push({
                resourcesType: RESOURCES_TYPE.BUNDLE,
                resPathOrName: bundleInfo.name,
                loadText: '加载场景资源',
                onBundleLoaded: (bundle) => {
                    bundleInfo.bundle = bundle;
                    managers().gameMgr.setMainModeLoaded(bundleInfo);
                }
            })
            //
            this.m_allPreloadResources.push({
                resourcesType: RESOURCES_TYPE.SCENE,
                resPathOrName: bundleInfo.sceneName,
                loadText: '加载主场景资源',
            })
        }
    }

    async loadAllPreloadResources(): Promise<void> {
        //
        this.initPreloadResources();
        //
        await this.startPreloadResources();
        await O1HD.getManagers().csvDataManager.initCsvList();

        //
        return Promise.resolve();
    }

    //开始加载数据
    async startPreloadResources(): Promise<void> {
        const {length} = this.m_allPreloadResources;
        for (let i = 0; i < length; i++) {
            let time1:number = Date.now();
            let currLoad = this.m_allPreloadResources[i];
            //
            let startProgress = i / length;
            this.setLoadProgress(startProgress, currLoad.loadText);
            //
            await this.preloadOneResources(currLoad, startProgress);
            let time2:number = Date.now();
            console.log(`加载${currLoad.loadText}耗时${time2 - time1}`);
        }

        return Promise.resolve();
    }

    //加载一个
    async preloadOneResources(currLoad: oneSonLoadProgress, startProgress: number): Promise<void> {
        return new Promise(resolve => {
            const {resourcesType, resPathOrName, bundle, onBundleLoaded, onComplete} = currLoad;
            //资源类型
            switch (resourcesType) {
                //分包
                case RESOURCES_TYPE.BUNDLE: {
                    cc.assetManager.loadBundle(resPathOrName, (err, bundle) => {
                        onBundleLoaded && onBundleLoaded(bundle);
                        resolve();
                    });
                    break;
                }
                case RESOURCES_TYPE.ASSETS: {
                    bundle().loadDir(resPathOrName, (finish, total) => {
                        this.setSonLoadProgress(finish / total, startProgress);
                    }, (error, assets) => {
                        onComplete && onComplete(error, assets);
                        resolve();
                    })
                    break;
                }
                case RESOURCES_TYPE.SCENE: {
                    cc.director.preloadScene(resPathOrName, (completedCount, totalCount) => {
                        this.setSonLoadProgress(completedCount / totalCount, startProgress);
                    }, error => {
                        resolve();
                    })
                    break;
                }
            }
        })
    }

    preLoadSceneOver(mainSceneName: string) {
        O1HD.loadScene(mainSceneName, () => {
        O1HD.getManagers().gameMgr.onGameRun();
        loading.isLoaded = true;
        // this.pmLoadBar.node.active = false;
        // this.logo.active = true;
        // this.startBtn.active = true;
        // this.newBtn.active =true;
        // this.attentionBtn.active=true;
        // this.loadingAni.node.active = false;
        O1HD.getServices() &&  O1HD.getServices().miniGameSrv.getAppApiInstance &&  O1HD.getServices().miniGameSrv.getAppApiInstance() &&  O1HD.getServices().miniGameSrv.getAppApiInstance().WidgetfullScreen &&  O1HD.getServices().miniGameSrv.getAppApiInstance().WidgetfullScreen();  //屏幕适配
            });
        // })
    }

    private setSonLoadProgress(progress: number, startProgress: number) {
        this.pmSonLoadBar.progress = progress;
        const length = this.m_allPreloadResources.length;
        this.setLoadProgress(startProgress + progress / length);
    }

    private setLoadProgress(progress: number, text?: string) {
        // console.log(progress,"进度>>>>>>>>>")
        this.pmLoadBar.progress = progress;
        this.loadingAni.setProgress(progress);
        if (text) {
            this.pmLoadLabel.string = `${text}(${(progress * 99.99).toFixed(2)}%)`;
        }
    }

    static isLoaded:boolean = false;

    onBtnStart(e, custom: string){
        if(loading.isLoaded){
            managers().soundMgr.playSound("mainSound/anNiu");
            managers().soundMgr.playVibrate();
            const mode = Number(custom);
            let levelMenuPrams = {
                mode: mode
            }
            mainRoot.UISystem.OpenPage(PAGE.LEVELMENU, levelMenuPrams);
        }else{
            O1HD.getModules().uiControlModule.showMessageBox("游戏正在加载中...");
        }
    }

}

